package com.wanbatv.wanba.jianshencao.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wanba.jianshencao.R;
import com.wanbatv.wanba.jianshencao.util.AppUtil;
import com.wanbatv.wanba.jianshencao.util.Crypto;
import com.wanbatv.wanba.jianshencao.util.Util;
import com.wanbatv.wanba.jianshencao.utils.Product;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.ffcs.itvpay.ItvPayTask;

/**
 * Created by ricardo on 2016/10/21.
 */
public class WebActivity extends FullScreenActivity{
    private WebView webview;
    JSONArray arr_zhifubao=null;
    JSONArray arr_zhifubao2=null;
    String orderInfo=null;
    String orderInfo1=null;
    public static String ISZHIFU="nopay";
    public static String ISZHIFUWWB="nopay";
    public static boolean IF_ZHIFU=false;
    private Bean bean;
    private ArrayList<String> list;
    private ArrayList<String> list1;
    private MediaPlayer mediaPlayer;
    private String product="pro";
    private String product_dog="pro";
    private String product_wd="pro";
    String wd;
    private String jsc;
    private String dog;
    private String wudao;
    private String now="zj_focus";
    private String fromhd;
    String string;
    private String fromwudao;
    private String login;

    private String click;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay);
        webview = ((WebView) findViewById(R.id.web));


        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);

        dinggou();
        is_dinggou();
        list = new ArrayList<>();
        list1 = new ArrayList<>();
        getUser();
        //Log.d("ricardo",AppUtil.STB.Sn+"@@"+AppUtil.STB.Model+"@@");
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(new JavaScriptObject(),"abc");
        if (AppUtil.STB.Model.equals("E8205")){
            //webview.loadUrl("file:///android_asset/huodong8205.html");
            webview.loadUrl("http://61.191.46.214:8080/activity/huodong8025.html");
        }else{
            //webview.loadUrl("file:///android_asset/huodong.html");
            webview.loadUrl("http://61.191.46.214:8080/activity/huodong1.html");
        }
        //webview.loadUrl("http://61.191.46.214:8080/activity/huodong.html");
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url!=null){
                    webview.loadUrl(url);
                }
                return true;
            }
        });
        webview.setVerticalScrollBarEnabled(false);
        webview.setBackgroundColor(getResources().getColor(android.R.color.transparent));



        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.freedom);
        mediaPlayer.start();

    }
    private void dinggou(){
        Log.d("ricardo","jianquan");

        String need_jiami= "itvAccount="+AppUtil.STB.UserID+"|"+"productId=zg_wanba";
        String orderInfo=jiami(need_jiami);

        try {
            orderInfo= URLEncoder.encode(orderInfo,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url  ="http://61.191.45.118:7002/itv-api"+"/has_order?providerId="+"shzg"+"&orderInfo="+orderInfo;
        RequestQueue rq = Volley.newRequestQueue(getApplicationContext());
        StringRequest request=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("response:",response);
                try {
                    JSONObject obj = new JSONObject(response);
                    int num=obj.getInt("ordered");
                    Log.d("rrrrr",num+"");
                    if(num!=0){
                        LoginActivity.IS_DINGGOU =true;
                        WebActivity.ISZHIFU="pay";
                    }else {
                        LoginActivity.IS_DINGGOU =false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        rq.add(request);


    }

    private void  is_dinggou2(){
        RequestQueue rq_1 = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest request_1 = new JsonObjectRequest("http://117.71.18.5/121.201.14.248/8062/adjxtag/api/common/wpay/check/"+Product.appId+"?userid="+ Util.getDeviceId(getApplicationContext())+"&flavor=anhui", null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            IF_ZHIFU=obj.getBoolean("payCompleted");
                            if (IF_ZHIFU){
                                WebActivity.ISZHIFUWWB="pay";
                            }else {
                                WebActivity.ISZHIFUWWB="nopay";
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = getPackageManager().getPackageInfo("com.wanbatv.wangwangba", 0);
                    headers.put("accept", "applicationnd.com.wanbatv.wangwangba;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        rq_1.add(request_1);
    }
    private void is_dinggou(){

        String need_jiami= "itvAccount="+AppUtil.STB.UserID+"|"+"productId=zg_wwb";
        String orderInfo=jiami(need_jiami);

        try {
            orderInfo= URLEncoder.encode(orderInfo,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url="http://61.191.45.118:7002/itv-api"+"/has_order?providerId="+"shzg"+"&orderInfo="+orderInfo+"&flavor=anhui";
        RequestQueue rq = Volley.newRequestQueue(getApplicationContext());
        StringRequest request=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("response:",response);
                try {
                    JSONObject obj = new JSONObject(response);
                    int num=obj.getInt("ordered");

                    if(num!=0){
                        IF_ZHIFU=true;
                        WebActivity.ISZHIFUWWB="pay";
                    }else {
                        IF_ZHIFU=false;
                        is_dinggou2();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        rq.add(request);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("ricardo",keyCode+"!!");

        if (keyCode==KeyEvent.KEYCODE_BACK&&webview.canGoBack()){
            webview.goBack();
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            Log.d("ricardo","onstop");
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

    public class JavaScriptObject{
        String abc="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
        @JavascriptInterface
        public void funFromJsc(){
            Log.d("ricardo","fromjsc");
            new Throwable().printStackTrace();
            chanpinbaojsc();
        }
        @JavascriptInterface
        public void funFromWd(){
            Log.d("ricardo","funfromwd");
            chanpinbaowd();
        }
        @JavascriptInterface
        public String isZhiFu(){
            if(LoginActivity.IS_DINGGOU){
                return "pay";
            }
            return WebActivity.ISZHIFU;
        }
        @JavascriptInterface
        public String isZhiFuDog(){
            if (IF_ZHIFU){
                return "pay";
            }
            return WebActivity.ISZHIFUWWB;
        }
        @JavascriptInterface
        public String isZhiFuWd(){
            if (LoginActivity.IS_DINGGOU){
                return "pay";
            }
            return WebActivity.ISZHIFU;
        }
        @JavascriptInterface
        public void fromAndroidDog(){
            chanpinbaodog();
        }
        @JavascriptInterface
        public void toJianShenCao(){
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            intent.putExtra("fromweb","web");
            startActivity(intent);
        }
        @JavascriptInterface
        public void toWudao(){
            Intent intent = getPackageManager().getLaunchIntentForPackage("wanba.wanbatv.com.wudao");
            intent.putExtra("from","jsc");
            startActivity(intent);
            finish();
        }
        @JavascriptInterface
        public void toWangWangba(){
            if (haveDog()){
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.wanbatv.wangwangba");
                intent.putExtra("from","jsc");
                startActivity(intent);
                finish();
            }else {
                Intent intent = getPackageManager().getLaunchIntentForPackage("com.amt.appstore");
                intent.putExtra("extraKey","account=&jumpId=8&contentId=386");
                startActivity(intent);
                finish();
            }
        }
        @JavascriptInterface
        public String FromAndroid(){
            String s="p5501******"+abc+"2016-12-1"+abc+"翼支付现金15元,"+"p5506******"+abc+"2016-12-1"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-1"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-2"+abc+"翼支付现金15元,"
                    +"p5506******"+abc+"2016-12-3"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-5"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-5"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-6"+abc+"翼支付现金15元,"
                    +"p5501******"+abc+"2016-12-6"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-6"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-6"+abc+"翼支付现金15元,"+"p5501******"+abc+"2016-12-6"+abc+"翼支付现金15元,";
            for (int i=0;i<list.size();i++){

                s+=list.get(i)+",";
            }
            return s;
        }

    }
    private void chanpinbaodog(){
        RequestQueue rq_2 = Volley.newRequestQueue(WebActivity.this.getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.245/121.201.14.248/8062/adjxtag/api/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor=anhui", null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            arr_zhifubao2=arr;
                            dingdanhaodog();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = WebActivity.this.getPackageManager().getPackageInfo(WebActivity.this.getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };


        rq_2.add(request_2);
    }
    private void dingdanhaodog(){
        try {
            JSONObject obj = arr_zhifubao2.getJSONObject(0);
            final   String subject=obj.getString("subject");
            final   String subjectid=obj.getString("subjectId");
            final   String price=obj.getString("price");
            RequestQueue requestQueue = Volley.newRequestQueue(WebActivity.this);
            String url="http://61.191.46.245/121.201.14.248/8062/adjxtag/api/common/wpay/getorder"+"?flavor=anhui";
            StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            product_dog="dog";

                            try {
                                JSONObject obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();
                                JSONObject oobj=obj_zhifubao.getJSONObject("data");
                                String order=oobj.getString("order");
                                orderInfo1="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wwb"+"|price=1500";
                                orderInfo1=jiami(orderInfo1);
                                ItvPayTask itvPayTask = new ItvPayTask(WebActivity.this);
                                HashMap<String, String> data = new HashMap<String, String>();
                                data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
                                data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
                                data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
//								data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
                                data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
                                data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
                                data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
                                data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
                                data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
                                data.put(ItvPayTask.ORDERINFO, orderInfo1);//订单信息
                                data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
                                Log.d("@@ricardo",data+"");
                                itvPayTask.pay(data);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    PackageInfo pi= null;
                    try {
                        pi = WebActivity.this.getPackageManager().getPackageInfo(WebActivity.this.getPackageName(), 0);
                        headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                        headers.put("app_version", pi.versionName);
                        headers.put("app_package_name",pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    // MyLog.d(TAG, "headers=" + headers);
                    return headers;
                }
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
                }
                @Override
                protected Map<String, String> getParams() {
                    //在这里设置需要post的参数
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("partner","");
                    params.put("subject", subject);
                    params.put("subjectid",subjectid);
                    params.put("price",price);
                    params.put("provider","ahpay");
                    params.put("stb", Util.getDeviceId(WebActivity.this));
                    params.put("flavor", Product.flavor);

                    return params;
                }
            };
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void chanpinbaojsc(){
        RequestQueue rq_2 = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.214:8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d("ricardo","chanpinbao");
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            arr_zhifubao=arr;
                            //Toast.makeText(getApplicationContext(),obj+"@@",Toast.LENGTH_LONG).show();
                            dingdanhaojsc();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

        rq_2.add(request_2);
    }
    private  void dingdanhaojsc(){

        try {
            JSONObject obj = arr_zhifubao.getJSONObject(0);
            final   String subject=obj.getString("subject");
            final   String subjectid=obj.getString("subjectId");
            final   String price=obj.getString("price");
            //Toast.makeText(getApplicationContext(),obj+"==",Toast.LENGTH_SHORT).show();
            RequestQueue requestQueue = Volley.newRequestQueue(WebActivity.this);
            String url="http://61.191.46.214:8087/postapi/common/wpay/getorder";
            StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            Log.d("riacrdo","dingdan");
                            product="jsc";

                            try {

                                JSONObject obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();
                                //Toast.makeText(getApplicationContext(),obj_zhifubao+"  @  @  "+Util.getDeviceId(getApplicationContext()),Toast.LENGTH_LONG).show();
                                JSONObject oobj=obj_zhifubao.getJSONObject("data");
                                String order=oobj.getString("order");
                                Log.d("@ricardo@", "get subject "+obj_zhifubao);
                                orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
                                orderInfo=jiami(orderInfo);
                                Log.d("@ricardo@",AppUtil.STB.Sn+"@@"+AppUtil.STB.IP+"@@"+AppUtil.STB.UserID);
                                ItvPayTask itvPayTask = new ItvPayTask(WebActivity.this);
                                HashMap<String, String> data = new HashMap<String, String>();
                                data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
                                data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
                                data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
                                //	data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
                                data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
                                data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
                                data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
                                data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
                                data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
                                data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
                                data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
                                itvPayTask.pay(data);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(),"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

                    error.printStackTrace();
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    PackageInfo pi= null;
                    try {
                        pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                        headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
                        headers.put("app_version", pi.versionName);
                        headers.put("app_package_name",pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    // MyLog.d(TAG, "headers=" + headers);
                    return headers;
                }
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
                }
                @Override
                protected Map<String, String> getParams() {
                    //在这里设置需要post的参数
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("partner","");
                    params.put("subject", subject);
                    params.put("subjectid",subjectid);
                    params.put("price",price);
                    params.put("provider","ahpay");
                    params.put("stb", Util.getDeviceId(getApplicationContext()));
                    params.put("flavor", Product.flavor);

                    return params;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(),"eeeee",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    private  void chanpinbaowd(){
        RequestQueue rq_2 = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.214:8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            arr_zhifubao2=arr;
                            Log.d("ricardo",arr+"");
                            //Toast.makeText(getApplicationContext(),obj+"@@",Toast.LENGTH_LONG).show();
                            dingdanhaowd();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

        rq_2.add(request_2);
    }
    private void dingdanhaowd(){
        try {
            JSONObject obj = arr_zhifubao2.getJSONObject(0);
            final   String subject=obj.getString("subject");
            final   String subjectid=obj.getString("subjectId");
            final   String price=obj.getString("price");
            //Toast.makeText(getApplicationContext(),obj+"==",Toast.LENGTH_SHORT).show();
            RequestQueue requestQueue = Volley.newRequestQueue(WebActivity.this);
            String url="http://61.191.46.214:8087/postapi/common/wpay/getorder";
            StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            product_wd="wd";
                            try {

                                JSONObject obj_zhifubao = (JSONObject) new JSONTokener(response).nextValue();
                                //Toast.makeText(getApplicationContext(),obj_zhifubao+"  @  @  "+Util.getDeviceId(getApplicationContext()),Toast.LENGTH_LONG).show();
                                Log.d("ricardo","obj"+obj_zhifubao);
                                JSONObject oobj=obj_zhifubao.getJSONObject("data");
                                String order=oobj.getString("order");
                                Log.d("@ricardo@", "get subject "+obj_zhifubao);
                                orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
                                orderInfo=jiami(orderInfo);
                                Log.d("@ricardo@",AppUtil.STB.Sn+"@@"+AppUtil.STB.IP+"@@"+AppUtil.STB.UserID);
                                ItvPayTask itvPayTask = new ItvPayTask(WebActivity.this);
                                HashMap<String, String> data = new HashMap<String, String>();
                                data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
                                data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
                                data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
                                //	data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
                                data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
                                data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
                                data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
                                data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
                                data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
                                data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
                                data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
                                itvPayTask.pay(data);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(),"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

                    error.printStackTrace();
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    PackageInfo pi= null;
                    try {
                        pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                        headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
                        headers.put("app_version", pi.versionName);
                        headers.put("app_package_name",pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    // MyLog.d(TAG, "headers=" + headers);
                    return headers;
                }
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
                }
                @Override
                protected Map<String, String> getParams() {
                    //在这里设置需要post的参数
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("partner","");
                    params.put("subject", subject);
                    params.put("subjectid",subjectid);
                    params.put("price",price);
                    params.put("provider","ahpay");
                    params.put("stb", Util.getDeviceId(getApplicationContext()));
                    params.put("flavor", Product.flavor);

                    return params;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(),"eeeee",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    private  String jiami(String orderInfo){
//        String msg = "使用3DES对数据进行加密";
//        byte[] secretArr = DES3Utils.encryptMode(msg.getBytes());
//        String jiami=Base64.encodeToString(secretArr,Base64.DEFAULT);
//        String res = null;
//        try {
//            res = new String(DES3Utils.decryptMode(Base64.decode(jiami, Base64.DEFAULT)), "utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.e("jiami","3des result " + msg.equals(res) + " res " + res + ", encrypt " + jiami);

        String jiami= Crypto.TripleDES.encrypt(orderInfo,"26f545c0d092463185acdd3e2c73fdda");
//        String jiami=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
        Log.e("jiami",jiami);
//        Log.e("jiemi",jiemi);
        return jiami;
    }
    private boolean haveDog(){
        PackageInfo packageInfo=null;
        try {
            packageInfo = getPackageManager().getPackageInfo("com.wanbatv.wangwangba", 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo=null;
            e.printStackTrace();
        }
        if (packageInfo==null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ItvPayTask.REQUEST_ITYPAY&&resultCode==ItvPayTask.RESULT_ITVPAY) {
            String result = data.getStringExtra("result");
            //Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
            //Log.d("ricardo@@",data.getStringExtra("providerId"));
            try {
                JSONObject obj=(JSONObject) new JSONTokener(result).nextValue();
                Log.d("ricardo@@@",obj+"");
                if(!obj.getString("tradeInfo").equals("") ){
                    Log.d("ricardo",product+"@@");
                    if (product.equals("jsc")){
                        Log.d("ricardo","tojsc");
                        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                        startActivity(intent);
                        WebActivity.ISZHIFU="pay";
                    }else if (product_wd.equals("wd")){
                        Log.d("ricardo","towudao");
                        Intent intent = getPackageManager().getLaunchIntentForPackage("wanba.wanbatv.com.wudao");
                        startActivity(intent);
                        WebActivity.ISZHIFU="pay";
                    }else if (product_dog.equals("dog")){
                        if (haveDog()){
                            Intent intent = getPackageManager().getLaunchIntentForPackage("com.wanbatv.wangwangba");
                            startActivity(intent);
                            WebActivity.ISZHIFUWWB="pay";
                        }else {
                            Intent intent = getPackageManager().getLaunchIntentForPackage("com.amt.appstore");
                            intent.putExtra("extraKey","account=&jumpId=8&contentId=386");
                            startActivity(intent);
                            WebActivity.ISZHIFUWWB="pay";
                        }


                    }
                    LoginActivity.IS_DINGGOU =true;
                    postUser();
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("huidiao",result);
        }
    }
    public void postUser() {
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        String url = "http://61.191.46.214:8064/addrecord";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<>();
                map.put("userid",AppUtil.STB.UserID);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(3000,3,1.0f));
        requestQueue.add(stringRequest);

    }
    public void getUser(){
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://61.191.46.214:8064/getrecord", null, new Response.Listener<JSONObject>() {


            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray resultData = response.getJSONArray("resultData");
                    for (int i=0;i<resultData.length();i++){
                        JSONObject jsonObject = resultData.getJSONObject(i);
                        String userId = jsonObject.getString("userId");
                        String payedTime = jsonObject.getString("payedTime");
                        bean = new Bean();
                        bean.setId(userId);
                        bean.setTime(payedTime);
                        String s = bean.toString();
                        list.add(s);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(3000,3,1.0f));
        requestQueue.add(jsonObjectRequest);
    }
    public class Bean{
        String id;
        String time;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        @Override
        public String toString() {
            String abc="&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
            time=time.substring(0,10);
            if (id.length()>=8){
                id=id.substring(0,5)+"******";
            }else if (id.length()==7){
                id=id.substring(0,5)+"******";
            }else if (id.length()==6){
                id=id.substring(0,5)+"******";
            }
            return id+abc+time+abc+"翼支付现金15元";
        }
    }

}
